<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>history前端路由模式</title>
</head>

<body>
  <div id="app">

    <ul>
      <li to="/home">首页</li>
      <li to="/list">列表页</li>
      <li to="/center">个人中心</li>
    </ul>

    <div id="content"></div>

  </div>

  <script>
    const home = {
      template: `<div>我是一个首页</div>`
    }
    const list = {
      template: `<div>我是列表页面</div>`
    }
    const center = {
      template: `<div>我是个人中心页面</div>`
    }

    // 路由规则匹配表
    const routes = [
      {
        path: '/home',
        component: home
      },
      {
        path: '/list',
        component: list
      },
      {
        path: '/center',
        component: center
      }
    ]

    // history前端路由模式，它的路由跳转只支持 js方式的跳转 ==> 编程式导航
    document.querySelectorAll('li').forEach(node => {
      node.addEventListener('click', function () {
        const path = this.getAttribute('to')
        render(path)
      })
    })

    window.addEventListener('popstate', function () {
      render(location.pathname)
    })


    function render(path) {
      const route = routes.find(item => item.path == path)
      // 匹配成功
      let component = ''
      if (route) {
        component = route.component.template
      }
      history.pushState({}, '', path)
      document.querySelector('#content').innerHTML = component
    }



  </script>
</body>

</html>